package com.longg.controller.user;

import com.longg.comm.Comm;
import com.longg.controller.BaseController;
import com.longg.model.Dept;
import com.longg.model.User;
import com.longg.model.UserFocus;
import com.longg.service.IDeptService;
import com.longg.service.IUserFocusService;
import com.longg.service.IUserInfoService;
import com.longg.service.IUserService;
import com.longg.service.impl.DeptServiceImpl;
import com.longg.service.impl.UserFocusServiceImpl;
import com.longg.service.impl.UserInfoServiceImpl;
import com.longg.service.impl.UserServiceImpl;
import com.longg.utils.PageUtil;
import com.longg.utils.StrUtil;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserController extends BaseController {
    private IUserService service = new UserServiceImpl();
    private IDeptService deptService = new DeptServiceImpl();
    private IUserInfoService userInfoService = new UserInfoServiceImpl();
    private IUserFocusService userFocusService = new UserFocusServiceImpl();

    public void showPersonal(HttpServletRequest req, HttpServletResponse resp){
        String id = req.getParameter("uid");
        HttpSession session = req.getSession();

        try {
            Map<String,Object> infoMap = service.getUserInfo(id);
            List<Dept> deptList = deptService.findAll();
            session.setAttribute("infoMap",infoMap);
            session.setAttribute("deptList",deptList);
            resp.sendRedirect(req.getContextPath() + "/assets/html/user_look.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void saveUserInfo(HttpServletRequest req, HttpServletResponse resp){
        boolean isSuccess = true;
        String saveMsg = "保存成功";
        HttpSession session = req.getSession();

        String id = req.getParameter("userId");
        String realName = req.getParameter("realName");
        String deptName = req.getParameter("deptName");
        String phone = req.getParameter("phone");
        String age = req.getParameter("age");
        String gender = req.getParameter("sex");
        String isSecret = req.getParameter("isSecret");
        isSecret = isSecret == null?"0":"1";
        isSuccess = service.updateInfo(Integer.parseInt(id),isSecret,deptName)
                && userInfoService.updateInfo(Integer.parseInt(id),realName,phone,age,gender);

        if(!isSuccess){
            saveMsg = "保存失败！";
        }

        session.setAttribute("saveMsg",saveMsg);
        try {
            resp.sendRedirect(req.getContextPath() + "/user/showPersonal?uid=" + id);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public void userList(HttpServletRequest req, HttpServletResponse resp){
        int currentPage = 1;
        HttpSession session = req.getSession();
        String page = req.getParameter("currentPage");
        if(null != page && !"".equals(page)){
            currentPage = Integer.parseInt(page);
        }
        int id = getUserId(req);
        String name = req.getParameter("name");
        List<Map<String, Object>> usersByPage = service.findUsersByPage(currentPage,id,name);
        long count = userInfoService.getCount(name);
        long totalPage = PageUtil.getTotalPage(count);
        long startPage = PageUtil.getStartPage(currentPage);
        long endPage = PageUtil.getEndPage(currentPage,count);
        session.setAttribute("currentPage",currentPage);
        session.setAttribute("count",count);
        session.setAttribute("totalPage",totalPage);
        session.setAttribute("startPage",startPage);
        session.setAttribute("endPage",endPage);
        session.setAttribute("usersByPage",usersByPage);
        session.setAttribute("pageCount",Comm.PAGE_COUNT);
        session.setAttribute("name",name);
        try {
            resp.sendRedirect(req.getContextPath() + "/assets/html/user.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void onFocus(HttpServletRequest req, HttpServletResponse resp){
        String fuidstr = req.getParameter("fuid");
        int uid = getUserId(req);
        int fuid = Integer.parseInt(fuidstr);
        try {
            if(uid == fuid){
                resp.getWriter().write("不能关注自己！");
            }else{
                UserFocus userFocus = userFocusService.ifFocus(uid, fuid);
                if(null != userFocus){
                    resp.getWriter().write("请不要重复关注！");
                }else {
                    int i = userFocusService.focus(uid,fuidstr);
                    if (1 > 1){
                        resp.getWriter().write("关注失败！");
                    }else{
                        resp.getWriter().write("1");
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void offFocus(HttpServletRequest req, HttpServletResponse resp){
        String fuidstr = req.getParameter("fuid");
        int uid = getUserId(req);
        UserFocus userFocus = userFocusService.ifFocus(uid, Integer.parseInt(fuidstr));

        try {
            if(null == userFocus){
                resp.getWriter().write("操作频繁！");
            }else{
                int i = userFocusService.deleteById(userFocus.getId());
                if (0 < i){
                    resp.getWriter().write("1");
                }else{
                    resp.getWriter().write("取关失败");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void findFocus(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        String pageStr = req.getParameter("currentPage");
        if(null == pageStr || "".equals(pageStr)){
            pageStr = "1";
        }
        int page = Integer.parseInt(pageStr);
        int id = getUserId(req);
        List<Map<String, Object>> userFocusList = userFocusService.findFocus(id,page);
        long count = userFocusService.getFocusCount(id);
        long totalPage = PageUtil.getTotalPage(count);
        long startPage = PageUtil.getStartPage(page);
        long endPage = PageUtil.getEndPage(page,count);
        session.setAttribute("userFocusList",userFocusList);
        session.setAttribute("totalPage",totalPage);
        session.setAttribute("startPage",startPage);
        session.setAttribute("endPage",endPage);
        session.setAttribute("currentPage",page);
        session.setAttribute("pageCount",Comm.PAGE_COUNT);
        try {
            resp.sendRedirect(req.getContextPath() + "/assets/html/my_user.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void uploadImg(HttpServletRequest req, HttpServletResponse resp){
        InputStream inputStream = null;
        FileOutputStream fos = null;
        try {
            ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
            List<FileItem> list = servletFileUpload.parseRequest(req);
            FileItem fileItem = null;
            if(!list.isEmpty()){
                fileItem = list.get(0);
            }
            if(null != fileItem){
                String name = fileItem.getName();
                if(!name.contains(Comm.IMG_FORMAT)){
                    resp.getWriter().write("暂只支持jpg格式");
                }else {
                    inputStream = fileItem.getInputStream();
                    name = StrUtil.getUUIDCode() + Comm.IMG_FORMAT;
                    fos = new FileOutputStream(Comm.IMG_PATH + name);
                    byte[] bytes = new byte[4 * 1024];
                    int len;
                    while(-1 != (len = inputStream.read(bytes))){
                        fos.write(bytes,0,len);
                    }
                    String path = "/upload/" + name;
                    resp.getWriter().write(path);
                    //将数据库的图片路径改了
                    int id = getUserId(req);
                    int i = userInfoService.updateImg(id,path);
                    String username = getUserName(req);
                    Map<String,Object> userInfoMap = service.getUserBaseInfo(username);
                    req.getSession().setAttribute("userInfoMap",userInfoMap);
                }
            }else{
                resp.getWriter().write("传入文件错误");
            }
        } catch (FileUploadException | IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(null != inputStream){
                    inputStream.close();
                }
                if (null != fos){
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public void showUserDetail(HttpServletRequest req, HttpServletResponse resp){
        HttpSession session = req.getSession();
        String uid = req.getParameter("uid");
        if(null == uid || "".equals(uid)){
            uid = "0";
        }
        Map<String,Object> infoMap = service.getUserInfo(uid);
        session.setAttribute("userDetail",infoMap);
        try {
            resp.sendRedirect(req.getContextPath() + "/assets/html/user_detail.jsp");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
